package pilgun.Multithread.ConnectionPool;

import java.sql.SQLException;
import java.util.concurrent.ThreadLocalRandom;

class getAndPut implements Runnable{
private static int MIN_WAITINGTIME = 1000;
private static int MAX_WAITINGTIME = 6000;
private ConnectionPool pool;
	
	public getAndPut(ConnectionPool pool) {
	this.pool = pool;
}

	public void run() {
		try {
			Connection c = pool.checkOut();
			int waitTime = ThreadLocalRandom.current().nextInt(MIN_WAITINGTIME,MAX_WAITINGTIME);  
			Thread.sleep(waitTime);
			c.close();
			Thread.sleep(waitTime);
			c = pool.checkOut();
			Thread.sleep(waitTime);
			pool.checkIn(c);
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (TooLongException e) {
			e.printStackTrace();
		}
		
	}

}

public class ConnectionPoolTry {
	private static int MAX_THREADS = 8;
	public static void main(String[] args) {
		ConnectionPool pool;
		try {
//			Class.forName("com.mysql.jdbc.Driver").newInstance();
//			pool = new ConnectionPool("jdbc:mysql://localhost:3306/ems", "root", "");
			Class.forName("org.h2.Driver").newInstance();
			pool = new ConnectionPool("jdbc:h2:c:/h2", "test", "");
			for (int i=0;i<MAX_THREADS;i++){
				Thread t = new Thread(new getAndPut(pool));
				t.start();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
	}
	
}
